package com.zishi.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zishi.model.pojo.User;
import com.zishi.service.UserService;
import com.zishi.util.ConstUtil;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author TP
 * @since 2022-05-05 08:53:41
 */
@RestController
@RequestMapping("/zishi/user")
@Log4j
public class UserController {

    @Autowired
    private UserService userService;

    // TODO 插入用户时将saveOneUser里的用户头像上传到服务器并赋给图片地址到user.favicon
    // TODO 新建一个接口,可以单独修改用头像

    /**
     * 获取所有用户信息
     */
    @GetMapping("")
    public List<User> getAllUser() {
        return userService.list();
    }

    /**
     * 根据openId获取用户主键id
     */
    @GetMapping("/openid/{openid}")
    public Integer getUserIdByOpenid(@PathVariable String openid) {
        return userService.getUserIdByOpenId(openid);
    }

    /**
     * 根据id获取用户
     */
    @GetMapping("/id/{id}")
    public User getUser(@PathVariable Integer id) {
        return userService.getById(id);
    }

    /**
     * 插入单个用户，返回主键id
     */
    @PostMapping("")
    public Integer insertOneUser(User user){
        userService.save(user);
        return user.getId();
    }


    /**
     * 批量插入用户
     */
    @PostMapping("/mcreate")
    public boolean insertBatchUser(ArrayList<User> users){
        return userService.saveBatch(users);
    }

    /**
     * 根据id更新用户
     */
    @PutMapping("/{id}")
    public boolean updateUserById(User user, @PathVariable Integer id) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        userService.update(user, wrapper.eq("id", id));
        return userService.updateById(user);
    }

    /**
     * 根据用户主键id更新用户头像
     */
    @PostMapping("/favicon/{openid}")
    public String updateUserFavicon(MultipartFile file, @PathVariable  String openid) {
        if (file.isEmpty()) {
            log.error("文件为空");
            return null;
        }

        return userService.updateUserFavicon(file, openid);
    }

    /**
     * 根据id删除用户
     */
    @DeleteMapping("/{id}")
    public boolean deleteUserById(@PathVariable Integer id) {
        return userService.removeById(id);
    }
}
